package com.hiveway.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hiveway.constant.MessageConstant;
import com.hiveway.constant.StatusConstant;
import com.hiveway.dto.CategoryDTO;
import com.hiveway.dto.CategoryPageQueryDTO;
import com.hiveway.entity.Category;
import com.hiveway.exception.DeletionNotAllowedException;
import com.hiveway.mapper.CategoryMapper;
import com.hiveway.mapper.DishMapper;
import com.hiveway.mapper.SetmealMapper;
import com.hiveway.result.PageResult;
import com.hiveway.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */
    public void save(CategoryDTO categoryDTO) {
        // 调整排序
        adjustSortValues(categoryDTO.getSort(), categoryDTO.getType(), null);

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.insert(category);
    }

    /**
     * 分页查询
     *
     * @param categoryPageQueryDTO
     * @return
     */
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id删除分类
     *
     * @param id
     */
    public void deleteById(Long id) {
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Integer count = dishMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealMapper.countByCategoryId(id);
        if (count > 0) {
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除分类数据
        categoryMapper.deleteById(id);
    }

    /**
     * 修改分类
     *
     * @param categoryDTO
     */
    public void update(CategoryDTO categoryDTO) {
        //获取原本的sort值
        Category original = categoryMapper.selectById(categoryDTO.getId());

        // 当排序值变化时才调整
        if (!categoryDTO.getSort().equals(original.getSort())) {
            adjustSortValues(categoryDTO.getSort(), original.getType(), categoryDTO.getId());
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    /**
     * 启用、禁用分类
     *
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();
        categoryMapper.update(category);
    }

    /**
     * 根据类型查询分类
     *
     * @param type
     * @return
     */
    public List<Category> list(Integer type) {
        List<Category> list = categoryMapper.list(type);
        return list;
    }

    /**
     * 调整分类排序（新增/修改时调用）
     *
     * @param newSort   新的排序值
     * @param type      分类类型
     * @param excludeId 需要排除的ID（修改时传入）
     */
    @Transactional
    public void adjustSortValues(Integer newSort, Integer type, Long excludeId) {
        // 获取同类型所有分类（按sort升序排列）
        //List<Category> categories = categoryMapper.listByTypeOrderBySort(type);
        List<Category> categories = categoryMapper.listOrderBySort();

        // 找到需要调整的记录（排除当前分类）
        categories.stream()
                .filter(c -> c.getSort() >= newSort && !c.getId().equals(excludeId))
                .forEach(c -> {
                    c.setSort(c.getSort() + 1);
                    categoryMapper.updateSort(c.getId(), c.getSort());
                });
    }


}



